package org.aalku.spring.remoting.server;

import org.aalku.springTest.launcher.MainLauncher;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.servlet.ServletHolder;
import org.mortbay.jetty.webapp.WebAppContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.web.context.support.XmlWebApplicationContext;

/**
 * Clase que arranca un servidor jetty y expone en el por hessian los servicios
 * exportados en hessian-exported-services.xml
 * 
 * Requiere un determinado application-context-jetty.xml
 */
public class JettyRemotingServer implements ApplicationContextAware,
		InitializingBean {

	private static final String PATH_SPEC = "/r/*";
	private static final String CLASSPATH_APPLICATION_CONTEXT_JETTY_XML = "classpath:/fixed/application-context-jetty.xml";
	private static final String CONTEXT_ATTRIBUTE = MainLauncher.class
			.getName() + ".appContext";
	private ApplicationContext applicationContext;

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}

	public void afterPropertiesSet() throws Exception {
		// spring WebApplicationContext
		XmlWebApplicationContext springWebApplicationContext = new XmlWebApplicationContext();
		springWebApplicationContext.setParent(applicationContext);
		springWebApplicationContext
				.setConfigLocation(CLASSPATH_APPLICATION_CONTEXT_JETTY_XML);
		springWebApplicationContext.refresh();

		// jetty WebAppContext
		WebAppContext sc = springWebApplicationContext
				.getBean(WebAppContext.class);
		sc.setAttribute(CONTEXT_ATTRIBUTE, springWebApplicationContext);

		// DispatcherServlet
		org.springframework.web.servlet.DispatcherServlet dispatcherServlet = springWebApplicationContext
				.getBean(org.springframework.web.servlet.DispatcherServlet.class);
		sc.addServlet(new ServletHolder(dispatcherServlet), PATH_SPEC);
		dispatcherServlet.setContextAttribute(CONTEXT_ATTRIBUTE);

		Server server = springWebApplicationContext.getBean(Server.class);
		server.start();
	}

}
